package me.hgj.jetpackmvvm.state

import androidx.lifecycle.MutableLiveData
import me.hgj.jetpackmvvm.network.AppException
import me.hgj.jetpackmvvm.network.BaseResponse
import me.hgj.jetpackmvvm.network.ExceptionHandle

/**
 * 作者　: hegaojian
 * 时间　: 2020/4/9
 * 描述　: 自定义结果集封装类
 */
sealed class ResultStateNoData<out T> {
    companion object {
        fun <T> onAppSuccess(): ResultStateNoData<T> = Success("")
        fun <T> onAppLoading(loadingMessage: String): ResultStateNoData<T> = Loading(loadingMessage)
        fun <T> onAppError(error: AppException): ResultStateNoData<T> = Error(error)
    }

    data class Loading(val loadingMessage: String) : ResultStateNoData<Nothing>()
    data class Success<out T>(val data: String) : ResultStateNoData<T>()
    data class Error(val error: AppException) : ResultStateNoData<Nothing>()
}

/**
 * 处理返回值
 * @param result 请求结果
 */
fun <T> MutableLiveData<ResultStateNoData<T>>.paresResultNoData(result: BaseResponse<T>) {
    value = when {
        result.isSucces() -> {
            ResultStateNoData.onAppSuccess()
        }
        else -> {

            ResultStateNoData.onAppError(
                AppException(
                    result.getResponseCode(),
                    result.getResponseMsg()
                )
            )
        }
    }
}

/**
 * 不处理返回值 直接返回请求结果
 * @param result 请求结果
 */

fun <T> MutableLiveData<ResultStateNoData<T>>.paresNoDataResult(result: T) {
    value = ResultStateNoData.onAppSuccess()
}

/**
 * 异常转换异常处理
 */

fun <T> MutableLiveData<ResultStateNoData<T>>.paresNoDataException(e: Throwable) {
    this.value = ResultStateNoData.onAppError(ExceptionHandle.handleException(e))
}

